//
//  HttpUtil.m
//  SinaWebo
//
//  Created by Pink Elephant on 15/4/14.
//  Copyright (c) 2015年 亦心. All rights reserved.
//

#import "HttpUtil.h"
#import "AFNetworking.h"

@interface HttpUtil ()
@property (strong, nonatomic) AFHTTPSessionManager *manager;
@end

@implementation HttpUtil

+ (instancetype)sharedHttpUtil{
    static HttpUtil *sharedClass;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedClass = [[HttpUtil alloc] init];
    });
    return sharedClass;
}

+(void)cancelManager{
    [[HttpUtil sharedHttpUtil].manager.tasks makeObjectsPerformSelector:@selector(cancel)];
}

- (AFHTTPSessionManager *)manager{
    if (_manager == nil) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}


+(void)postWithURL:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
//    [HttpUtil sharedHttpUtil].manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    [HttpUtil sharedHttpUtil].manager.acceptableContentTypes =
    [[HttpUtil sharedHttpUtil].manager POST:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            failure(error);
        }
    }];
}

+(void)getWithURL:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    [[HttpUtil sharedHttpUtil].manager GET:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            failure(error);
        }
    }];
}

+(void)postWithURL:(NSString *)url params:(NSDictionary *)params formDataArray:(NSArray *)formDataArray success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    [[HttpUtil sharedHttpUtil].manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (FormData *data in formDataArray) {
            [formData appendPartWithFileData:data.data name:data.name fileName:data.filename mimeType:data.mimeType];
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            failure(error);
        }
    }];
}

@end
